package com.mz.ozy.activity.shop;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.activity.MainActivity;
import com.mz.ozy.adapter.CartListAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.CartListBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.FirmCartBean;
import com.mz.ozy.bean.FirmOrderBean;
import com.mz.ozy.bean.GoodsListBean;
import com.mz.ozy.bean.ShoppingCartListBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.CarPresenter;
import com.mz.ozy.mvp.view.CarContract;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CarActivity extends BaseActivity<CarContract.View, CarPresenter> implements CarContract.View {

    private static Activity sPreActivity;
    @BindView(R.id.titleBar)
    RelativeLayout mTitleBar;
    @BindView(R.id.rl_mall_bottom)
    RelativeLayout mRlMallBottom;
    @BindView(R.id.ll_top_title)
    LinearLayout mLlTopTitle;
    //    @BindView(R.id.rv_content)
//    RecyclerView mRvContent;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout mSrlRefresh;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;
    @BindView(R.id.iv_icon_empty)
    ImageView mIvIconEmpty;
    @BindView(R.id.fl_view_empty)
    LinearLayout mFlViewEmpty;
    @BindView(R.id.tv_back_home)
    TextView mTvBackHome;
    @BindView(R.id.iv_all_select)
    ImageView mIvAllSelect;
    @BindView(R.id.ll_real_payment)
    LinearLayout mLlRealPayment;
    @BindView(R.id.tv_real_payment)
    TextView mTvRealPayment;
    @BindView(R.id.tv_discount_price)
    TextView mTvDiscountPrice;
    @BindView(R.id.tv_real_num)
    TextView mTvRealNum;

    @BindView(R.id.car_guess)
    LinearLayout car_guess;
    @BindView(R.id.gridview)
    RecyclerView mGridview;

    private boolean isAllCarCheck = false;
    private CartListAdapter mSearchAdapter;
    private List<GoodsListBean.GoodsPageBean.PageItemsBean> mBeanList = new ArrayList<>();
    private List<CartListBean> mCarList = new ArrayList<>();
    private List<FirmCartBean> mFirmGoodsBeans = new ArrayList<>();
    private List<FirmCartBean> diffFirmGoodsBeans = new ArrayList<>();

    private long curTime;
    private boolean isEditType;
    private int tag;
    private int page = 1;
    private boolean isFirstLoad = true;

    private int totalNum = 0;
    private double totalPrice = 0.00;
    private double totalMarketPrice = 0.00;
    private double totalDiscountPrice = 0.00;
    private FirmCartBean mSelectCartBean;
    private int mSelectIndex;

    public static void go(Activity activity) {
        sPreActivity = activity;
        activity.startActivity(new Intent(activity, CarActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initTitle();
        tvCenterTitle.setText(R.string.shop_car);
        titleBar.setBackgroundColor(getResources().getColor(R.color.white));
        initData();
        initView();
    }

    private void initData() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstLoad) {
            refreshList();
        }
        isFirstLoad = false;
    }

    @Override
    public void onInitSuccess(ShoppingCartListBean bean) {
        if (tag == 0) {
            mSrlRefresh.setLoadmoreFinished(false);
            mSrlRefresh.finishRefresh();
            mCarList.clear();
            mFirmGoodsBeans.clear();
            mSelectCartBean = null;
            mSelectIndex = 0;
            mRvPresaleList.removeAllViews();
            mPresaleListView.clear();
            if (bean.getpList().size() == 0) {
                rightTextView.setVisibility(View.GONE);
                mFlViewEmpty.setVisibility(View.VISIBLE);
                mRlMallBottom.setVisibility(View.GONE);
//                mLlTopTitle.setVisibility(View.GONE);
            } else {
                rightTextView.setVisibility(View.VISIBLE);
                mFlViewEmpty.setVisibility(View.GONE);
                mRlMallBottom.setVisibility(View.VISIBLE);
//                mLlTopTitle.setVisibility(View.VISIBLE);
            }
        } else if (tag == 1) {
            mSrlRefresh.finishLoadmore();
        }
        mCarList.addAll(bean.getpList());
        processCarList();
        if (bean.getList() != null && bean.getList().size() > 0) {
            mSearchAdapter.setNewData(bean.getList());
        }
    }

    @BindView(R.id.rv_presales_list)
    LinearLayout mRvPresaleList;
    private List<View> mPresaleListView = new ArrayList<>();

    private void processCarList() {
        if (mCarList != null) {
            for (CartListBean productMapBean : mCarList) {
                if (productMapBean.getType() == 1) {
                    productMapBean.setProducttype(3);
                }

                FirmCartBean firmGoodsBeanList = null;
                if (!TextUtils.isEmpty(productMapBean.getStarttime())) {
                    Date date = null;
                    try {
                        date = CalendarUtils.string2Date(productMapBean.getStarttime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (curTime < date.getTime()) {
                        firmGoodsBeanList = getFirmGoodsBeanList(productMapBean.getStarttime(), productMapBean.getProducttype());
                    } else {

                        for (FirmCartBean firmGoodsBean : mFirmGoodsBeans) {

                            if (firmGoodsBean.getProducttype() == productMapBean.getProducttype()) {
                                firmGoodsBeanList = firmGoodsBean;
                            }
                        }
                        productMapBean.setStarttime("");

                    }
                } else {

                    productMapBean.setStarttime("");
                    firmGoodsBeanList = getFirmGoodsBeanList("", productMapBean.getProducttype());
                    if (firmGoodsBeanList != null && productMapBean.getProducttype() != firmGoodsBeanList.getProducttype()) {
                        firmGoodsBeanList = null;

                    }

                }
                if (firmGoodsBeanList == null) {
                    firmGoodsBeanList = new FirmCartBean();
                    firmGoodsBeanList.setProducttype(productMapBean.getProducttype());
                    firmGoodsBeanList.setMarket_price(Double.parseDouble(productMapBean.getMarket_price()));
                    firmGoodsBeanList.setDate(productMapBean.getStarttime());
                    firmGoodsBeanList.addProduct(productMapBean);
                    if (!TextUtils.isEmpty(productMapBean.getStarttime())) {
                        mFirmGoodsBeans.add(firmGoodsBeanList);
                    } else if (productMapBean.getProducttype() == 1) {
                        mFirmGoodsBeans.add(firmGoodsBeanList);
                    } else if (productMapBean.getProducttype() == 0) {
                        mFirmGoodsBeans.add(firmGoodsBeanList);
                    } else if (productMapBean.getProducttype() == 3) {
                        mFirmGoodsBeans.add(firmGoodsBeanList);
                    }
                } else {
                    firmGoodsBeanList.setProducttype(productMapBean.getProducttype());
                    firmGoodsBeanList.addProduct(productMapBean);
                }

            }

            processPresalesList();
        }
    }

    private void processPresalesList() {
        if (mFirmGoodsBeans.size() == 0) {
            mRvPresaleList.setVisibility(View.GONE);
        } else {
            for (FirmCartBean firmGoodsBean : mFirmGoodsBeans) {
                final View presaleOrderView = View.inflate(this, R.layout.item_car_order_presale, null);
                mPresaleListView.add(presaleOrderView);
                mRvPresaleList.addView(presaleOrderView);
                processPresalesView(presaleOrderView, firmGoodsBean);
                LinearLayout rvPresaleList = presaleOrderView.findViewById(R.id.rv_presale_goods_list);
                if (firmGoodsBean.getCarList().size() == 0) {
                    rvPresaleList.setVisibility(View.GONE);
                } else {
                    for (int i = 0; i < firmGoodsBean.getCarList().size(); i++) {
                        CartListBean productMapBean = firmGoodsBean.getCarList().get(i);
                        productMapBean.setIndex(i);
                        final View submitOrderView = View.inflate(this, R.layout.view_item_car_goods, null);
                        processSubmitOrderView(submitOrderView, rvPresaleList, productMapBean, firmGoodsBean);
                    }
                }
            }
        }
    }

    //购物车物品
    private void processPresalesView(View presaleOrderView, FirmCartBean firmGoodsBean) {
        final TextView tvPresaleTime = presaleOrderView.findViewById(R.id.tv_presale_time);
        final TextView tvOrderName = presaleOrderView.findViewById(R.id.tv_order_name);
        final RelativeLayout rlSelect = presaleOrderView.findViewById(R.id.rl_select);
        final ImageView ivSelect = presaleOrderView.findViewById(R.id.iv_select);
        final String formatDate = firmGoodsBean.getFormatDate();
        if (!TextUtils.isEmpty(formatDate)) {
            Log.e("TAG", "预售商品");
            tvOrderName.setText("预售商品");
            tvOrderName.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_car_order, 0, 0, 0);
            tvPresaleTime.setText("开售时间" + formatDate);
        } else if (firmGoodsBean.getProducttype() == 3) {
            Log.e("TAG", "积分");
            tvOrderName.setText("积分");
            tvOrderName.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_car_oh, 0, 0, 0);
            tvPresaleTime.setVisibility(View.GONE);
        } else if (firmGoodsBean.getProducttype() == 1) {
            Log.e("TAG", "欧花商品");
            tvOrderName.setText("欧花商品");
            tvOrderName.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_car_oh, 0, 0, 0);
            tvPresaleTime.setVisibility(View.GONE);
        } else if (firmGoodsBean.getProducttype() == 0) {
            Log.e("TAG", "商品清单");
            tvOrderName.setText("商品清单");
            tvOrderName.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_car_shop, 0, 0, 0);
            tvPresaleTime.setVisibility(View.GONE);
        }

//        else if (firmGoodsBean.getProducttype() == 2) {
//            tvOrderName.setText("积分商品");
//            tvOrderName.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_car_shop, 0, 0, 0);
//            tvPresaleTime.setVisibility(View.GONE);
//        }

        firmGoodsBean.setCurImageView(ivSelect);
        rlSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSelectCartBean = firmGoodsBean;
                minusTotal();
                mSelectCartBean.setCarCheck();
                addTotal();
                mTvRealNum.setText("共" + totalNum + "件");
                setBtnSubmit();
                mTvRealPayment.setText(getPrice(totalPrice - totalDiscountPrice));
                setTotalDiscountPrice();
                setAllCheckState();
            }
        });
    }

    private void processSubmitOrderView(View submitOrderView, LinearLayout rvGoodsList, CartListBean productMapBean, FirmCartBean firmGoodsBean) {
        rvGoodsList.addView(submitOrderView);
        TextView ivMinus = submitOrderView.findViewById(R.id.iv_minus);
        TextView ivMinusBig = submitOrderView.findViewById(R.id.iv_minus_big);
        TextView ivAdd = submitOrderView.findViewById(R.id.iv_add);
        TextView ivAddBig = submitOrderView.findViewById(R.id.iv_add_big);
        RelativeLayout rlSelect = submitOrderView.findViewById(R.id.rl_select);
        RelativeLayout rlItemView = submitOrderView.findViewById(R.id.rl_item_view);
        TextView tvGoodsCount = submitOrderView.findViewById(R.id.tv_goods_count);
        ImageView ivSelect = submitOrderView.findViewById(R.id.iv_select);
        TextView tvTitle = submitOrderView.findViewById(R.id.tv_title);
        ImageView ivIcon = submitOrderView.findViewById(R.id.iv_icon);
        TextView tvInfo = submitOrderView.findViewById(R.id.tv_info);
        TextView tvMoney = submitOrderView.findViewById(R.id.tv_money);
        TextView tvCarActivity = submitOrderView.findViewById(R.id.tv_car_activity);
        firmGoodsBean.addTextViews(tvGoodsCount);
        firmGoodsBean.addImageViews(ivSelect);
        addOrderViewEvents(ivMinusBig, ivAddBig, rlSelect, ivSelect, rlItemView, productMapBean, firmGoodsBean);

        String imgUrl = "";
        if (!TextUtils.isEmpty(productMapBean.getImg_zt())) {
            final String[] img_arr = productMapBean.getImg_zt().trim().split(",");
            if (img_arr.length > 0) {
                imgUrl = img_arr[0];
            }
        }
        GlideUtils.loadRoundImg(this, ivIcon, imgUrl, R.mipmap.default_foods_icon, 4);
        if (productMapBean.check()) {
            ivSelect.setImageResource(R.mipmap.cb_red_select);
        } else {
            ivSelect.setImageResource(R.mipmap.cb_red_normal);
        }
        if (TextUtils.isEmpty(productMapBean.getActivityName())) {
            tvCarActivity.setVisibility(View.GONE);
        } else {
            tvCarActivity.setVisibility(View.VISIBLE);
            tvCarActivity.setText(productMapBean.getActivityName());
        }
        tvMoney.setText(getPrice(productMapBean));
        tvGoodsCount.setText(String.valueOf(productMapBean.getNum()));
        tvTitle.setText(productMapBean.getTradename());
        tvInfo.setText(productMapBean.getName());
    }

    private void addOrderViewEvents(TextView ivMinus, TextView ivAdd, RelativeLayout rlSelect, final ImageView ivSelect, RelativeLayout rlItemView, final CartListBean productMapBean, final FirmCartBean firmGoodsBean) {
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSelectCartBean = firmGoodsBean;
                mSelectIndex = productMapBean.getIndex();
                mPresenter.operateGoods(CarActivity.this, String.valueOf(productMapBean.getId()), "1");
            }
        });
        ivMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (productMapBean.getNum() < 2) {
                    ToastUtils.showToast("商品数不能小于1");
                    return;
                }
                mSelectCartBean = firmGoodsBean;
                mSelectIndex = productMapBean.getIndex();
                mPresenter.operateGoods(CarActivity.this, String.valueOf(productMapBean.getId()), "2");
            }
        });
        rlSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSelectCartBean = firmGoodsBean;
                productMapBean.setCheck(!productMapBean.check());
                minusTotal();
                mSelectCartBean.setItemCheck(productMapBean.getIndex());
                addTotal();
                mTvRealNum.setText("共" + totalNum + "件");
                setBtnSubmit();
                mTvRealPayment.setText(getPrice(totalPrice - totalDiscountPrice));
                setTotalDiscountPrice();
                setAllCheckState();
            }
        });
        rlItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CarActivity.this, ShopDetailActivity.class);
                intent.putExtra("goodsId", productMapBean.getProduct_id());
                startActivity(intent);
            }
        });
    }

    private void setTotalDiscountPrice() {
        if (totalDiscountPrice > 0.0) {
            mTvDiscountPrice.setVisibility(View.VISIBLE);

            double obTotalDiscountPrice = culObTotalDiscountPrice();

            // totalDiscountPrice = totalDiscountPrice - obTotalDiscountPrice;

            if (obTotalDiscountPrice > 0) {

                if (totalDiscountPrice - obTotalDiscountPrice == 0) {
                    mTvDiscountPrice.setText("共优惠" + Utils.subTwoNumber(obTotalDiscountPrice) + "欧花");

                } else {
                    mTvDiscountPrice.setText("共优惠" + Utils.subTwoNumber(totalDiscountPrice - obTotalDiscountPrice) + "元+" + Utils.subTwoNumber(obTotalDiscountPrice) + "欧花");

                }


            } else {
                mTvDiscountPrice.setText("共优惠" + Utils.subTwoNumber(totalDiscountPrice - obTotalDiscountPrice) + "元");

            }


        } else {
            mTvDiscountPrice.setVisibility(View.GONE);
        }
    }

    private FirmCartBean getFirmGoodsBeanList(String starttime, int type) {
        for (FirmCartBean firmGoodsBean : mFirmGoodsBeans) {
            if (TextUtils.isEmpty(firmGoodsBean.getDate()) && TextUtils.isEmpty(starttime)) {
                return firmGoodsBean;
            } else if (!TextUtils.isEmpty(firmGoodsBean.getDate()) && firmGoodsBean.getDate().equals(starttime)) {
                return firmGoodsBean;
            }
        }
        return null;
    }

    @Override
    public void onInitError(String msg) {
        mSrlRefresh.finishRefresh();
        mFlViewEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDeleteGoodsSuccess() {
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
    }

    @Override
    public void onEditGoodsCountSuccess(String type) {
        if ("1".equals(type)) {
            minusTotal();
            mSelectCartBean.addSelectNum(mSelectIndex);
            addTotal();
            mTvRealNum.setText("共" + totalNum + "件");
            setBtnSubmit();
            mTvRealPayment.setText(getPrice(totalPrice - totalDiscountPrice));
            setTotalDiscountPrice();
        } else if ("2".equals(type)) {
            minusTotal();
            mSelectCartBean.minusSelectNum(mSelectIndex);
            addTotal();
            mTvRealNum.setText("共" + totalNum + "件");
            setBtnSubmit();
            mTvRealPayment.setText(getPrice(totalPrice - totalDiscountPrice));
            setTotalDiscountPrice();
        }
    }

    private void minusTotal() {
        totalNum = totalNum - mSelectCartBean.getTotalNum();
        totalPrice = totalPrice - mSelectCartBean.getTotalPrice();
        totalMarketPrice = totalMarketPrice - mSelectCartBean.getTotalMarketPrice();
        totalDiscountPrice = totalDiscountPrice - mSelectCartBean.getTotalDiscountPrice();
    }

    private void addTotal() {
        totalNum = totalNum + mSelectCartBean.getTotalNum();
        totalPrice = totalPrice + mSelectCartBean.getTotalPrice();
        totalMarketPrice = totalMarketPrice + mSelectCartBean.getTotalMarketPrice();
        totalDiscountPrice = totalDiscountPrice + mSelectCartBean.getTotalDiscountPrice();
    }

    @Override
    public void onSubmitSuccess(FirmOrderBean firmOrderBean, String cid) {
        //确认订单
//        finish();
//        mIvAllSelect.setImageResource(R.mipmap.cb_red_normal);
//        isAllCarCheck = false;
        FirmOrderActivity1.start(this, firmOrderBean, cid, "", 0);
    }

    @Override
    public void onSubmitError(String msg) {

        ToastUtils.showToast("提交失败!");
    }

    private String getPrice(CartListBean item) {
        String price = "";
        if (!TextUtils.isEmpty(item.getPrice()) && Double.parseDouble(item.getPrice()) != 0.00) {
            price += "¥";
            price += item.getPrice();
        }
        if (!TextUtils.isEmpty(item.getMarket_price()) && Double.parseDouble(item.getMarket_price()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += item.getMarket_price();
                price += "积分";
            } else {
                price += item.getMarket_price();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        if (item.getProducttype() == 1) {
            return price.replace("¥", "") + "欧花";
        }


        return price;
    }

    @NotNull
    private String getPrice(double curPrice) {
        double obPrice = culObPrice();
        double culObTotalDiscountPrice = culObTotalDiscountPrice();
        curPrice = curPrice - obPrice + culObTotalDiscountPrice;
        String price = "";
        if (curPrice != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(curPrice);
        }
        if (totalMarketPrice != 0.00) {
            //积分商品
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(totalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(totalMarketPrice);
                price += "积分";
            }
        }

        if (obPrice > 0) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(obPrice - culObTotalDiscountPrice);
                price += "欧花";
            } else {
                price += Utils.subTwoNumber(obPrice - culObTotalDiscountPrice);
                price += "欧花";
            }

        }

        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }


        return price;
    }

    //计算欧币总价
    public double culObPrice() {

        double ohPrice = 0.00;
        for (int i = 0; i < mFirmGoodsBeans.size(); i++) {
            FirmCartBean bean = mFirmGoodsBeans.get(i);

            for (int j = 0; j < bean.getCarList().size(); j++) {
                CartListBean cartListBean = bean.getCarList().get(j);
                if (cartListBean.isCheck() && cartListBean.getProducttype() == 1) {
                    ohPrice = ohPrice + Double.parseDouble(cartListBean.getPrice()) * cartListBean.getNum();
                }
            }
        }

        return ohPrice;

    }

    //欧币折扣总价
    public double culObTotalDiscountPrice() {

        double price = 0.00;
        for (int i = 0; i < mFirmGoodsBeans.size(); i++) {
            FirmCartBean bean = mFirmGoodsBeans.get(i);
            double itemPrice = 0.00;
            for (int j = 0; j < bean.getCarList().size(); j++) {
                CartListBean cartListBean = bean.getCarList().get(j);
                if (cartListBean.isCheck() && cartListBean.getProducttype() == 1) {
                    itemPrice = bean.getTotalDiscountPrice();
                }
            }
            price = price + itemPrice;

        }

        return price;
    }


    private void initView() {
        tvTitle.setText(getString(R.string.shop_car));
        rightTextView.setText(R.string.edit_label);
        isEditType = false;
        mFlViewEmpty.setVisibility(View.GONE);
//        mLlTopTitle.setVisibility(View.GONE);
//        topLine.setVisibility(View.GONE);
//        mAdapter = new ShoppingCartAdapter(null);
//        mRvContent.setLayoutManager(new LinearLayoutManager(this));
//        mRvContent.setAdapter(mAdapter);

        boolean isok = SPUtils.getInstance(this).getBoolean(Constants.SPName.RECOMMEND, true);
        car_guess.setVisibility(isok ? View.VISIBLE : View.GONE);

        mGridview.setLayoutManager(new GridLayoutManager(this, 2));
        mSearchAdapter = new CartListAdapter(mBeanList);
        mGridview.setAdapter(mSearchAdapter);

        initEvents();
    }

    private void initEvents() {
        mSrlRefresh.setEnableLoadmore(false);
        mSrlRefresh.setOnRefreshListener(new OnRefreshListener() {
            //            @Override
//            public void onLoadmore(RefreshLayout refreshlayout) {
//                tag = 1;
//                page = page + 1;
//                mPresenter.initData(CarActivity.this, String.valueOf(page));
//            }
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshList();
            }
        });
        mIvAllSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isAllCarCheck) {
                    setAllCheckFalse();
                } else {
                    setAllCheckTrue();
                }
            }
        });

        mTvBackHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.tabHost.setCurrentTab(0);
                if (sPreActivity != null) {
                    sPreActivity.finish();
                }
                finish();
            }
        });

        mSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final GoodsListBean.GoodsPageBean.PageItemsBean item = mSearchAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view: {
                        Intent intent = new Intent(CarActivity.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", item.getId() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.iv_search_car: {
                        Intent intent = new Intent(CarActivity.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", item.getId() + "");
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
    }

    private void refreshList() {
        totalNum = 0;
        totalPrice = 0.00;
        totalMarketPrice = 0.00;
        totalDiscountPrice = 0.00;
        mTvRealNum.setText("共" + 0 + "件");
        setBtnSubmit();
        mTvRealPayment.setText("¥0.00");
        setTotalDiscountPrice();
        mIvAllSelect.setImageResource(R.mipmap.cb_red_normal);
        isAllCarCheck = false;
        tag = 0;
        page = 1;
        mPresenter.initData(CarActivity.this, String.valueOf(page), isFirstLoad);
    }

    private void setAllCheckFalse() {
        for (FirmCartBean bean : mFirmGoodsBeans) {
            bean.setAllCheck(false);
        }
        totalNum = 0;
        totalPrice = 0.00;
        totalMarketPrice = 0.00;
        totalDiscountPrice = 0.00;
        mTvRealNum.setText("共" + 0 + "件");
        setBtnSubmit();
        mTvRealPayment.setText("¥0.00");
        setTotalDiscountPrice();
        isAllCarCheck = false;
        mIvAllSelect.setImageResource(R.mipmap.cb_red_normal);
    }


    private void setAllCheckTrue() {
        totalNum = 0;
        totalPrice = 0.00;
        totalMarketPrice = 0.00;
        totalDiscountPrice = 0.00;
        for (FirmCartBean bean : mFirmGoodsBeans) {
            bean.setAllCheck(true);
            totalNum = totalNum + bean.getTotalNum();
            totalPrice = totalPrice + bean.getTotalPrice();
            totalMarketPrice = totalMarketPrice + bean.getTotalMarketPrice();
            totalDiscountPrice = totalDiscountPrice + bean.getTotalDiscountPrice();
        }
//                    mAdapter.notifyDataSetChanged();
        mTvRealNum.setText("共" + totalNum + "件");
        setBtnSubmit();
        mTvRealPayment.setText(getPrice(totalPrice - totalDiscountPrice));
        setTotalDiscountPrice();
        isAllCarCheck = true;
        mIvAllSelect.setImageResource(R.mipmap.cb_red_select);
    }

    private void setAllCheckState() {
        boolean isAllCheck = true;
        for (FirmCartBean bean : mFirmGoodsBeans) {
            if (!bean.setAllCheckState()) {
                isAllCheck = false;
                break;
            }
        }
        isAllCarCheck = isAllCheck;
        if (isAllCarCheck) {
            mIvAllSelect.setImageResource(R.mipmap.cb_red_select);
        } else {
            mIvAllSelect.setImageResource(R.mipmap.cb_red_normal);
        }
    }

    @OnClick({R.id.right, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right:
                if (isEditType) {
                    isEditType = false;
                    rightTextView.setText(R.string.edit_label);
                    setBtnSubmit();
                    mLlRealPayment.setVisibility(View.VISIBLE);
                } else {
                    isEditType = true;
                    rightTextView.setText(R.string.complete_label);
                    mBtnSubmit.setText("删除商品");
                    mBtnSubmit.setBackgroundColor(ContextCompat.getColor(this, R.color.c_fbcc14));
                    mLlRealPayment.setVisibility(View.GONE);
                }
                setAllCheckFalse();
                break;
            case R.id.btn_submit:
                if (isEditType) {
                    final BaseDialog dialog = new BaseDialog(this, R.layout.dialog_normal, Gravity.CENTER, true);

                    ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("确认删除吗?");
                    dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.toggleDialog();
                        }
                    });

                    dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //删除商品
                            deleteGoods();
                            dialog.toggleDialog();
                        }
                    });

                    dialog.toggleDialog();
                } else {

                    //提交购物车
                    submit();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if (event.getCode() == Constants.EventCode.REFRESH_CAR) {
            if (mPresenter != null) {
                totalNum = 0;
                totalPrice = 0.00;
                totalDiscountPrice = 0.00;
                mTvRealNum.setText("共" + 0 + "件");
                setBtnSubmit();
                mTvRealPayment.setText("¥0.00");
                setTotalDiscountPrice();
                mIvAllSelect.setImageResource(R.mipmap.cb_red_normal);
                isAllCarCheck = false;
                tag = 0;
                page = 1;
                mPresenter.initData(CarActivity.this, String.valueOf(page), isFirstLoad);
            }
        }
    }

    private void setBtnSubmit() {
        if (!isEditType) {
            if (totalNum != 0) {
                mBtnSubmit.setText("去结算(" + totalNum + ")");
            } else {
                mBtnSubmit.setText("去结算");
            }
            mBtnSubmit.setBackgroundColor(ContextCompat.getColor(this, R.color.c_73b21a));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //提交购物车
    private void submit() {
        if (mFirmGoodsBeans.isEmpty()) return;
        StringBuilder goodsList = new StringBuilder();
        boolean hasGoodsOrder = false;
        int commonOrder = 0;
        boolean hasOhOrder = false;//是否有欧花商品
        boolean hasNormalOrder = false;//是否普通商品
        boolean hasJfOrder = false;//是否积分商品


        for (int i = 0; i < mFirmGoodsBeans.size(); i++) {
            FirmCartBean bean = mFirmGoodsBeans.get(i);
            final String checkIds = bean.getCheckIds();
            goodsList.append(checkIds);
            if (TextUtils.isEmpty(bean.getDate()) && !TextUtils.isEmpty(checkIds)) {
                hasGoodsOrder = true;

                if (bean.getProducttype() == 1) {
                    hasOhOrder = true;
                }

                if (bean.getProducttype() == 0) {
                    hasNormalOrder = true;
                }

                if (bean.getProducttype() == 3) {
                    hasJfOrder = true;
                }

            }
            if (!TextUtils.isEmpty(bean.getDate()) && !TextUtils.isEmpty(checkIds)) {
                commonOrder++;
            }

        }
        if (hasGoodsOrder && commonOrder != 0) {
            ToastUtils.showToast("预售商品请单独提交");
            return;
        }
        if (commonOrder > 1) {
            ToastUtils.showToast("开售时间不同，请分开提交");
            return;
        }

        if (hasOhOrder && hasNormalOrder) {
            ToastUtils.showToast("欧花商品请单独提交订单");
            return;
        }

        if (hasOhOrder && hasJfOrder) {
            ToastUtils.showToast("积分商品请单独提交订单");
            return;
        }

        //没有选中商品
        if (goodsList.length() < 1) {
            ToastUtils.showToast("请选择商品");
            return;
        }
        mPresenter.submit(this, goodsList.substring(0, goodsList.length() - 1), "1", goodsList.substring(0, goodsList.length() - 1), totalNum);
    }

    //删除商品
    public void deleteGoods() {
        if (mFirmGoodsBeans.isEmpty()) return;
        StringBuilder goodsList = new StringBuilder();
        for (int i = 0; i < mFirmGoodsBeans.size(); i++) {
            FirmCartBean bean = mFirmGoodsBeans.get(i);
            goodsList.append(bean.getCheckIds());
        }
        //没有选中商品
        if (goodsList.length() < 1) {
            ToastUtils.showToast("请选择商品");
            return;
        }
        mPresenter.operateGoods(this, goodsList.substring(0, goodsList.length() - 1), "0");
    }
}
